﻿//-----------------------------------------------------------------------
// <copyright>
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace Fulcrum
{
    public class FulcrumGenerationUnitManager
    {
        public FulcrumGenerationUnitManager()
        {
            // nothing
        }

        public GenerationUnit GetGenerationUnit(string name)
        {
            foreach (var genUnit in this.GenerationUnits)
            {
                if (String.Equals(genUnit.Name, name, StringComparison.OrdinalIgnoreCase))
                {
                    return genUnit;
                }
            }

            throw new ApplicationException(String.Format("The generation unit '{0}' was not found.", name));
        }

        public void LoadGenerationUnits()
        {
            ComposeGenerationUnits();
        }

        protected virtual void ComposeGenerationUnits()
        {
            var catalog = new System.ComponentModel.Composition.Hosting.DirectoryCatalog(".");
            var container = new CompositionContainer(catalog);

            var batch = new CompositionBatch();
            batch.AddPart(this);

            container.Compose(batch);
        }

        [ImportMany]
        protected IEnumerable<GenerationUnit> GenerationUnits
        {
            get;
            set;
        }
    }
}
